﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using FriendsNearby.Services.Facebook;
using System.Transactions;
using Microsoft.Practices.EnterpriseLibrary.Data;
using FriendsNearby.Services.Entities;

namespace FriendsNearby.Services.Tests
{
    sealed class Protocols
    {
        public static void UserAddApplication(IServiceProvider system, string facebookUserId, string sessionKey)
        {
            var socialService = system.GetService<ISocialNetworkService, FacebookSocialNetworkService>();
            socialService.RegisterFacebookUser(facebookUserId, sessionKey);
        }

        public static void UserEntersPage(IServiceProvider system, string facebookUserId, string sessionKey)
        {
            var socialService = system.GetService<ISocialNetworkService, FacebookSocialNetworkService>();
            socialService.EnsureFacebookUserExists(facebookUserId, sessionKey);
        }

        public static void UserRemoveApplication(IServiceProvider system, string facebookUserId)
        {
            // before refactoring rev41
            // system.GetService<IUsersService>().UnregisterFacebookUser(facebookUserId);
        }

        public static Guid GetUserId(IServiceProvider system, string facebookUserID)
        {
            return system.GetService<IUsersService>().QueryUserRegistry(r => r.FacebookUserId == facebookUserID).UserID;
        }

        public static bool PreferencesWithDefaultValues(IServiceProvider system, Guid userID)
        {
            var pref = system.GetService<IUsersService>().GetUserPreferences(userID);
            return pref.NearbyRadiusKM == 50 && (VisibilityLevel) pref.VisibilityLevel == VisibilityLevel.ContactsAndTheirContacts;
        }

        public static Database CreateDatabase()
        {
            return DatabaseFactory.CreateDatabase("FriendsNearbyDB");
        }

        public static TransactionScope TemporalyClearDatabase()
        {
            var transaction = new TransactionScope();

            var database = CreateDatabase();

            database.ExecuteNonQuery(System.Data.CommandType.Text, "DELETE FROM LastUserNotification");
            database.ExecuteNonQuery(System.Data.CommandType.Text, "DELETE FROM LogTwitterMessages");
            database.ExecuteNonQuery(System.Data.CommandType.Text, "DELETE FROM SocialLog");
            database.ExecuteNonQuery(System.Data.CommandType.Text, "DELETE FROM UserLocationHistory");
            database.ExecuteNonQuery(System.Data.CommandType.Text, "DELETE FROM UserLocation");
            database.ExecuteNonQuery(System.Data.CommandType.Text, "DELETE FROM UserRegistry");

            return transaction;
        }
    }
}
